<template>
  <div class="search-suggestion">
    <van-cell @click="$emit('search-event',item)" icon="search" v-for="(item,index) in suggestions" :key="index">
      <div slot="title" v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>
<script>
// 防抖是最后一次
// 节流是频率触发一次
import { getSearchSuggestion } from '@/api/search'
// debounce 回弹
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: []
    }
  },
  computed: {},
  // watch不但可以监听data，也可以监听props，$route
  watch: {
    searchText: {
      handler: debounce(function () {
        this.getSearchSuggestion()
      }, 1000),
      immediate: true
    }
  },
  created () {},
  mounted () {

  },
  methods: {
    async getSearchSuggestion () {
      try {
        const res = await getSearchSuggestion(this.searchText)
        console.log(res)
        this.suggestions = res.data.data.options
      } catch (err) {
        console.log(err)
      }
    },
    highlight (str) {
      const reg = new RegExp(this.searchText, 'gi')
      return str.replace(reg, `<span style="color:red">${this.searchText}</span>`)
    }
  }
}
</script>

<style scoped lang="less"></style>
